<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>CarbonTrack Contributor Network</title>
  <link rel="icon" href="/img/team.jpg" type="image/JPG">
  <!-- Bootstrap and jQuery -->
  <link rel="stylesheet" href="./css/bootstrap.min.css">
  <script src="js/jquery.min.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
  <!-- SF Pro font -->
  <link href="https://fonts.cdnfonts.com/css/sf-pro-display" rel="stylesheet">
  <!-- Site CSS -->
  <link rel="stylesheet" href="./css/ios-design.css">
  <script src="js/utils.js"></script>
  <script src="js/nav.js"></script>
  <link rel="stylesheet" href="./css/index.css">
  <style>
    :root {
      /* Light mode colors */
      --text-color-light: #000;
      --text-color-dark: #fff;
      --bg-color-light: #f2f2f7;
      --bg-color-dark: #1c1c1e;
      --card-bg-light: #fff;
      --card-bg-dark: #2c2c2e;
      --border-color-light: #d1d1d6;
      --border-color-dark: #38383a;
      --muted-text-light: #8e8e93;
      --muted-text-dark: #aeaeb2;
      --map-bg-light: #3DA69A;
      --map-bg-dark: #2D7A71;
      --country-fill-light: #A1D1BF;
      --country-fill-dark: #5D8D7D;
      --marker-fill-light: #ff3b30;
      --marker-fill-dark: #ff6b60;
      --marker-stroke-light: white;
      --marker-stroke-dark: white;
      --animation-timing-apple: cubic-bezier(0.25, 0.1, 0.25, 1);
    }
    
    body {
      margin: 0;
      padding: 0;
      background-color: var(--bg-color-light);
      font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif;
      color: var(--text-color-light);
      transition: background-color 0.3s ease, color 0.3s ease;
      position: relative;
      min-height: 100vh;
    }

    /* Frosted glass background */
    .frosted-glass {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: -2;
      backdrop-filter: blur(20px);
      -webkit-backdrop-filter: blur(20px);
      background: rgba(255, 255, 255, 0.05);
    }
    
    /* Add ambient glow effects */
    .glow-effect {
      position: fixed;
      width: 300px;
      height: 300px;
      border-radius: 50%;
      filter: blur(50px);
      z-index: -1;
      opacity: 0.5;
      animation: pulse 8s infinite alternate var(--animation-timing-apple);
    }
    
    .glow-green {
      top: 10%;
      right: 10%;
      background: radial-gradient(circle, rgba(52, 199, 89, 0.2), transparent 70%);
    }
    
    .glow-blue {
      bottom: 10%;
      left: 5%;
      background: radial-gradient(circle, rgba(0, 122, 255, 0.15), transparent 70%);
      animation-delay: 2s;
    }
    
    @keyframes pulse {
      0% { transform: scale(1) translate(0, 0); opacity: 0.5; }
      50% { transform: scale(1.05) translate(20px, -10px); opacity: 0.7; }
      100% { transform: scale(1) translate(0, 0); opacity: 0.5; }
    }

    /* Dark mode styles */
    body.dark-theme,
    body.auto-theme.dark-mode {
      background-color: var(--bg-color-dark);
      color: var(--text-color-dark);
    }

    .block {
      background-color: var(--card-bg-light);
      border-radius: 24px;
      max-width: 1000px;
      margin: 30px auto;
      padding: 30px;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
      transition: background-color 0.3s ease, box-shadow 0.3s ease, transform 0.4s var(--animation-timing-apple);
      backdrop-filter: blur(20px);
      -webkit-backdrop-filter: blur(20px);
    }
    
    .block:hover {
      transform: translateY(-5px);
      box-shadow: 0 12px 30px rgba(0, 0, 0, 0.12);
    }

    body.dark-theme .block,
    body.auto-theme.dark-mode .block {
      background-color: var(--card-bg-dark);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    }

    .hero-header {
      background: linear-gradient(135deg, var(--ios-green), var(--ios-mint));
      color: white;
      padding: 120px 0 80px;
      text-align: center;
      border-radius: 0 0 24px 24px;
      margin-bottom: 40px;
      position: relative;
      overflow: hidden;
    }
    
    /* Add shimmer effect */
    .hero-header::before {
      content: '';
      position: absolute;
      top: -50%;
      left: -50%;
      width: 200%;
      height: 200%;
      background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 60%);
      transform: rotate(30deg);
      animation: shimmer 10s infinite linear;
      pointer-events: none;
    }
    
    @keyframes shimmer {
      0% { transform: translateX(-50%) rotate(0deg); }
      100% { transform: translateX(0%) rotate(360deg); }
    }
    
    .hero-header h1 {
      font-weight: 700;
      color: white;
      margin-bottom: 16px;
      font-size: 48px;
      opacity: 0;
      animation: fadeInUp 0.8s var(--animation-timing-apple) forwards;
    }
    
    .hero-header p {
      font-size: 1.2rem;
      opacity: 0;
      max-width: 800px;
      margin: 0 auto;
      animation: fadeInUp 0.8s var(--animation-timing-apple) 0.2s forwards;
    }
    
    @keyframes fadeInUp {
      from {
        opacity: 0;
        transform: translateY(20px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    #header {
      text-align: center;
    }
    
    #header h1 {
      margin: 0;
      font-size: 42px;
      font-weight: 700;
      background: linear-gradient(135deg, var(--ios-green), var(--ios-blue));
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      opacity: 0;
      animation: fadeInUp 0.8s var(--animation-timing-apple) 0.4s forwards;
    }
    
    #header h2 {
      margin: 20px 0 10px;
      font-size: 24px;
      font-weight: 600;
      color: var(--text-color-light);
      opacity: 0;
      animation: fadeInUp 0.8s var(--animation-timing-apple) 0.6s forwards;
    }
    
    body.dark-theme #header h2,
    body.auto-theme.dark-mode #header h2 {
      color: var(--text-color-dark);
    }
    
    #header p, #footer p {
      max-width: 800px;
      margin: 16px auto;
      line-height: 1.6;
      font-size: 18px;
      color: var(--text-color-light);
      opacity: 0;
      animation: fadeInUp 0.8s var(--animation-timing-apple) 0.8s forwards;
    }
    
    body.dark-theme #header p,
    body.auto-theme.dark-mode #header p,
    body.dark-theme #footer p,
    body.auto-theme.dark-mode #footer p {
      color: var(--text-color-dark);
    }
    
    #header h3 {
      margin: 30px 0 10px;
      font-size: 24px;
      font-weight: 600;
      color: var(--text-color-light);
      opacity: 0;
      animation: fadeInUp 0.8s var(--animation-timing-apple) 1s forwards;
    }
    
    body.dark-theme #header h3,
    body.auto-theme.dark-mode #header h3 {
      color: var(--text-color-dark);
    }

    #map-container {
      width: 100%;
      height: 70vh;
      position: relative;
      overflow: hidden;
      background: var(--map-bg-light);
      border-radius: 24px;
      transition: background-color 0.3s ease, transform 0.4s var(--animation-timing-apple);
      opacity: 0;
      animation: fadeInUp 0.8s var(--animation-timing-apple) 1.2s forwards;
    }
    
    body.dark-theme #map-container,
    body.auto-theme.dark-mode #map-container {
      background: var(--map-bg-dark);
    }
    
    svg {
      width: 100%;
      height: 100%;
      display: block;
    }

    .country {
      fill: var(--country-fill-light);
      stroke: rgba(255, 255, 255, 0.2);
      stroke-width: 0.5;
      transition: fill 0.3s ease, stroke 0.3s ease;
      cursor: pointer;
    }
    
    body.dark-theme .country,
    body.auto-theme.dark-mode .country {
      fill: var(--country-fill-dark);
    }

    body.dark-theme .country:hover,
    body.auto-theme.dark-mode .country:hover {
      fill: var(--country-fill-dark);
      filter: brightness(1.1);
    }

    .marker-container {
      transition: transform 0.3s ease;
      cursor: pointer;
    }
    
    /* Active state for marker containers */
    .marker-container.active .marker {
      fill: var(--ios-blue);
      stroke-width: 2px;
      transform: scale(1.1);
    }
    
    /* Enhance active markers in dark mode */
    body.dark-theme .marker-container.active .marker,
    body.auto-theme.dark-mode .marker-container.active .marker {
      fill: #5ac8fa; /* Bright blue in dark mode */
      stroke: white;
      stroke-width: 2.5px;
      filter: drop-shadow(0px 0px 3px rgba(90, 200, 250, 0.5));
    }

    .marker {
      fill: var(--marker-fill-light);
      stroke: var(--marker-stroke-light);
      stroke-width: 1.5;
      cursor: pointer;
      transition: fill 0.3s ease, transform 0.2s ease;
      transform-origin: center center;
    }

    .marker-pulse {
      fill: var(--marker-fill-light);
      fill-opacity: 0.3;
      animation: pulse-marker 2s infinite;
    }

    @keyframes pulse-marker {
      0% { r: 5; fill-opacity: 0.8; }
      70% { r: 15; fill-opacity: 0; }
      100% { r: 5; fill-opacity: 0; }
    }
    
    body.dark-theme .marker,
    body.auto-theme.dark-mode .marker {
      fill: var(--marker-fill-dark);
      stroke: var(--marker-stroke-dark);
      stroke-width: 2px; /* Thicker stroke in dark mode for better visibility */
    }

    body.dark-theme .marker-pulse,
    body.auto-theme.dark-mode .marker-pulse {
      fill: var(--marker-fill-dark);
    }
    
    .marker:hover {
      fill: var(--ios-blue);
    }

    /* Add enhanced hover effect for dark mode */
    body.dark-theme .marker:hover,
    body.auto-theme.dark-mode .marker:hover {
      fill: #5ac8fa; /* Brighter blue for dark mode hover */
      filter: brightness(1.2);
      transform: scale(1.05);
    }

    #popup {
      position: absolute;
      background: var(--card-bg-light);
      border: 1px solid var(--border-color-light);
      border-radius: 16px;
      padding: 16px;
      max-width: 300px;
      box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
      display: none;
      z-index: 10;
      animation: bounce 0.4s ease-out;
      pointer-events: auto;
      transition: background-color 0.3s ease, border-color 0.3s ease;
      transform-origin: center bottom;
      will-change: transform;
      overflow: auto;
      max-height: 60vh;
    }
    
    /* Add responsive styles for popup on mobile */
    @media (max-width: 768px) {
      #popup {
        max-width: 85vw; /* Wider popup on mobile */
        max-height: 50vh; /* Shorter max height on mobile to prevent overflow */
        padding: 12px; /* Smaller padding */
        font-size: 0.9em; /* Slightly smaller text */
      }
      
      #popup h3 {
        font-size: 16px;
        margin-bottom: 8px;
      }
      
      #popup p, #popup li {
        margin-bottom: 6px;
        font-size: 13px;
      }
    }
    
    body.dark-theme #popup,
    body.auto-theme.dark-mode #popup {
      background: var(--card-bg-dark);
      border-color: var(--border-color-dark);
    }
    
    @keyframes bounce {
      0% { transform: translateY(-20px) scale(0.8); opacity: 0; }
      60% { transform: translateY(5px) scale(1.02); opacity: 1; }
      100% { transform: translateY(0) scale(1); }
    }
    
    #popup h3 {
      margin: 0 0 10px 0;
      font-size: 18px;
      font-weight: 600;
      color: var(--text-color-light);
    }
    
    body.dark-theme #popup h3,
    body.auto-theme.dark-mode #popup h3 {
      color: var(--text-color-dark);
    }
    
    #popup p, #popup li {
      margin: 0 0 8px 0;
      font-size: 14px;
      line-height: 1.5;
      color: var(--text-color-light);
    }
    
    body.dark-theme #popup p,
    body.auto-theme.dark-mode #popup p,
    body.dark-theme #popup li,
    body.auto-theme.dark-mode #popup li {
      color: var(--text-color-dark);
    }
    
    #popup ul {
      padding-left: 20px;
      margin: 10px 0;
    }
    
    #popup strong {
      font-weight: 600;
      color: var(--ios-blue);
    }
    
    #footer {
      text-align: center;
      padding: 20px;
      opacity: 0;
      animation: fadeInUp 0.8s var(--animation-timing-apple) 1.4s forwards;
    }
    
    #footer h3 {
      margin: 0 0 16px 0;
      font-size: 28px;
      font-weight: 600;
      color: var(--text-color-light);
    }
    
    body.dark-theme #footer h3,
    body.auto-theme.dark-mode #footer h3 {
      color: var(--text-color-dark);
    }
    
    .join-button {
      display: inline-block;
      background: linear-gradient(135deg, var(--ios-green), var(--ios-mint));
      color: white;
      font-weight: 600;
      padding: 14px 32px;
      border-radius: 50px;
      text-decoration: none;
      margin-top: 16px;
      transition: transform 0.2s ease, box-shadow 0.2s ease;
      box-shadow: 0 4px 12px rgba(52, 199, 89, 0.3);
    }
    
    .join-button:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 16px rgba(52, 199, 89, 0.4);
      color: white;
      text-decoration: none;
    }
    
    /* Theme toggle button */
    .theme-toggle {
      position: fixed;
      right: 20px;
      bottom: 20px;
      width: 48px;
      height: 48px;
      border-radius: 24px;
      background-color: #f2f2f7;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      z-index: 1000;
      transition: all 0.3s ease;
    }

    body.dark-theme .theme-toggle,
    body.auto-theme.dark-mode .theme-toggle {
      background-color: #3a3a3c;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
    }

    .theme-toggle i {
      font-size: 22px;
      color: #8e8e93;
      transition: color 0.3s ease;
    }

    body.dark-theme .theme-toggle i,
    body.auto-theme.dark-mode .theme-toggle i {
      color: #fff;
    }
    
    /* Responsive styles */
    @media (max-width: 768px) {
      .hero-header {
        padding: 100px 0 60px;
      }
      
      .hero-header h1 {
        font-size: 36px;
      }
      
      #header h1 {
        font-size: 32px;
      }
      
      #header h2, #header h3 {
        font-size: 20px;
      }
      
      #header p, #footer p {
        font-size: 16px;
        padding: 0 15px;
      }
      
      #map-container {
        height: 50vh;
      }
      
      .block {
        margin: 20px 15px;
        padding: 20px;
      }
    }

    /* Custom scrollbar for popup */
    #popup::-webkit-scrollbar {
      width: 8px;
    }
    
    #popup::-webkit-scrollbar-track {
      background: transparent; /* Match popup background */
    }
    
    #popup::-webkit-scrollbar-thumb {
      background-color: rgba(142, 142, 147, 0.5); /* System gray */
      border-radius: 4px;
    }
    
    body.dark-theme #popup::-webkit-scrollbar-thumb,
    body.auto-theme.dark-mode #popup::-webkit-scrollbar-thumb {
      background-color: rgba(99, 99, 102, 0.7); /* Darker gray for dark mode */
    }

    .map-controls {
      position: absolute;
      bottom: 20px;
      right: 20px;
      display: flex;
      flex-direction: column;
      gap: 8px;
      z-index: 10;
    }

    .map-control-btn {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.9);
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      border: none;
      color: var(--map-bg-light);
      font-size: 18px;
      transition: all 0.2s ease;
    }

    .map-control-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
      background: white;
    }

    body.dark-theme .map-control-btn,
    body.auto-theme.dark-mode .map-control-btn {
      background: rgba(60, 60, 67, 0.9); /* More opaque for better visibility */
      color: white;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25); /* Stronger shadow for better visibility */
    }

    body.dark-theme .map-control-btn:hover,
    body.auto-theme.dark-mode .map-control-btn:hover {
      background: rgba(80, 80, 87, 0.95); /* Lighter on hover */
      transform: translateY(-2px);
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
    }

    .map-control-btn:active {
      transform: translateY(1px);
    }

    .map-region-label {
      font-size: 12px;
      font-weight: 600;
      fill: rgba(255, 255, 255, 0.7);
      text-anchor: middle;
      pointer-events: none;
      text-shadow: 0px 1px 3px rgba(0, 0, 0, 0.5);
    }
    
    body.dark-theme .map-region-label,
    body.auto-theme.dark-mode .map-region-label {
      fill: rgba(255, 255, 255, 0.9);
      text-shadow: 0px 1px 4px rgba(0, 0, 0, 0.8);
    }

    /* Back button style */
    .back-button {
      position: fixed;
      top: 80px; /* Move below the navbar */
      left: 20px;
      z-index: 1001; /* Ensure it's above other elements like theme toggle */
      background-color: rgba(50, 50, 50, 0.8); /* Darker, semi-transparent background */
      color: white;
      padding: 8px 16px;
      border-radius: 20px; /* Rounded corners like iOS */
      text-decoration: none;
      font-size: 14px;
      font-weight: 500;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
      transition: all 0.3s ease;
      border: 1px solid rgba(80, 80, 80, 0.5);
      backdrop-filter: blur(5px);
      -webkit-backdrop-filter: blur(5px);
    }

    .back-button:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
      text-decoration: none;
      color: white; /* Ensure text color remains on hover */
    }

    body.dark-theme .back-button,
    body.auto-theme.dark-mode .back-button {
      background-color: rgba(40, 40, 40, 0.8);
      color: white;
      border-color: rgba(70, 70, 70, 0.5);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    }

    body.dark-theme .back-button:hover,
    body.auto-theme.dark-mode .back-button:hover {
      color: white; /* Ensure text color remains on hover */
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
    }

    .back-button i {
      margin-right: 6px; /* Space between icon and text */
    }

    .feature-card {
      transition: transform 0.3s ease;
    }
    .feature-card:hover {
      background: var(--card-bg-light, white);
      transform: translateY(-5px);
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    }
  </style>
  <script>
    // To be executed after the page loads
    document.addEventListener('DOMContentLoaded', function() {
      // Theme toggle functionality
      // Check if user has a saved preference
      const savedTheme = localStorage.getItem('theme');
      const body = document.body;
      
      if (savedTheme) {
        body.className = savedTheme;
        updateThemeIcon(savedTheme);
      } else {
        body.classList.add('auto-theme');
        if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
          body.classList.add('dark-mode');
        }
        updateThemeIcon('auto-theme');
      }
      
      // Listen for system dark mode changes
      window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function(e) {
        if (body.classList.contains('auto-theme')) {
          if (e.matches) {
            body.classList.add('dark-mode');
          } else {
            body.classList.remove('dark-mode');
          }
          updateThemeIcon('auto-theme');
        }
      });
      
      // Create theme toggle button
      const themeToggle = document.createElement('div');
      themeToggle.className = 'theme-toggle';
      themeToggle.id = 'themeToggle';
      themeToggle.innerHTML = '<i class="fas fa-moon"></i>';
      document.body.appendChild(themeToggle);
      
      // Add click event to theme toggle
      themeToggle.addEventListener('click', function() {
        if (body.classList.contains('auto-theme')) {
          body.classList.remove('auto-theme');
          body.classList.remove('dark-mode');
          body.classList.add('dark-theme');
          localStorage.setItem('theme', 'dark-theme');
        } else if (body.classList.contains('dark-theme')) {
          body.classList.remove('dark-theme');
          body.classList.add('light-theme');
          localStorage.setItem('theme', 'light-theme');
        } else {
          body.classList.remove('light-theme');
          body.classList.add('auto-theme');
          if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
            body.classList.add('dark-mode');
          }
          localStorage.setItem('theme', 'auto-theme');
        }
        updateThemeIcon(body.className);
      });
      
      function updateThemeIcon(theme) {
        const icon = document.querySelector('#themeToggle i');
        if (!icon) return;
        
        if (theme.includes('dark-theme')) {
          icon.className = 'fas fa-sun';
        } else if (theme.includes('light-theme')) {
          icon.className = 'fas fa-moon';
        } else {
          // Auto theme
          if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
            icon.className = 'fas fa-sun';
          } else {
            icon.className = 'fas fa-moon';
          }
        }
      }
      
      // 全局点击事件监听器，用于关闭地图弹窗
      document.addEventListener('click', function(event) {
        const mapContainer = document.getElementById('map-container');
        const popup = document.getElementById('popup');
        
        // 如果点击的不是地图容器内的元素且弹窗可见，则隐藏弹窗
        if (popup && popup.style.display === 'block' && !mapContainer.contains(event.target)) {
          popup.style.display = 'none';
          isPopupSticky = false; // Reset sticky state when closing popup
          // 重置活动标记
          if (window.activeMarker) {
            window.activeMarker = null;
          }
        }
      });
    });
  </script>
</head>
<body class="auto-theme">
  <!-- Add back button -->
  <a href="about.html" class="back-button">
    <i class="fas fa-chevron-left"></i> Back
  </a>

  <!-- Add frosted glass background -->
  <div class="frosted-glass"></div>

  <!-- Add ambient glow effects -->
  <div class="glow-effect glow-green"></div>
  <div class="glow-effect glow-blue"></div>

  <!-- Navbar container, will be loaded by JavaScript -->
  <div id="navbar-container"></div>

  <!-- Hero Header -->
  <header class="hero-header">
    <div class="container">
      <h1>CarbonTrack Contributor Network</h1>
      <p>Global Youth, Creating a Sustainable Future Together</p>
    </div>
  </header>

  <div class="container">
    <div id="header" class="block">
      <h1>CarbonTrack Contributor Network 🌎</h1>
      <h2>Global Youth, Creating a Sustainable Future Together</h2>
      <p>
        CarbonTrack is empowering environmentally conscious youth from around the world.
        We cultivate a common drive across schools and communities, using CarbonTrack to track their carbon footprint,
        promote sustainable living styles, and drive real impact in their surroundings.
      </p>
      <h3>Where Our Contributors Are From</h3>
      <p>
        On this map, you can see the schools and communities our contributors come from.
        They actively promote sustainability within their campuses and engage in various initiatives
        within the CarbonTrack community.
      </p>
    </div>

    <div id="map-container" class="block">
      <svg id="map"></svg>
      <div id="popup"></div>
      <div class="map-controls">
        <button class="map-control-btn" id="zoomIn" aria-label="Zoom In">
          <i class="fas fa-plus"></i>
        </button>
        <button class="map-control-btn" id="zoomOut" aria-label="Zoom Out">
          <i class="fas fa-minus"></i>
        </button>
        <button class="map-control-btn" id="resetMap" aria-label="Reset Map">
          <i class="fas fa-undo"></i>
        </button>
      </div>
    </div>

    <div id="footer" class="block">
      <h3>Join Our Global Movement</h3>
      <p>
        If you're passionate about sustainability and want to be part of a global network of changemakers,
        we welcome you to join us! Together, we can create a more sustainable future for our planet.
      </p>
      <a href="about.html" class="join-button">Join Us Today</a>
    </div>
  </div>

  <!-- Footer placeholder -->
  <div id="footer-placeholder"></div>

  <script src="https://d3js.org/d3.v7.min.js"></script>
  <script>
    const container = document.getElementById("map-container");
    const width = container.clientWidth;
    const height = container.clientHeight;
    const svg = d3.select("#map");
    
    // Set up the zoom behavior
    const zoom = d3.zoom()
      .scaleExtent([1, 8])
      .on("zoom", zoomed);
      
    // Initialize map group with zoom support
    svg.call(zoom);
    const mapGroup = svg.append("g");

    // 创建分层的图层以确保正确的渲染顺序
    const countryLayer = mapGroup.append("g").attr("class", "country-layer");
    const markerLayer = mapGroup.append("g").attr("class", "marker-layer");
    const labelLayer = mapGroup.append("g").attr("class", "label-layer");

    // Define continent centers for quick navigation
    const continentCenters = {
      "northAmerica": { coords: [-100, 40], scale: 2.5 },
      "southAmerica": { coords: [-60, -15], scale: 2.5 },
      "europe": { coords: [15, 50], scale: 4 },
      "africa": { coords: [20, 0], scale: 2.5 },
      "asia": { coords: [100, 30], scale: 2 },
      "oceania": { coords: [135, -25], scale: 3 }
    };

    const projection = d3.geoEquirectangular()
      .center([0, 20]) // Shift to see more of northern hemisphere
      .rotate([-10, 0]); // Slight rotation for better view
    const path = d3.geoPath(projection);
    
    // Set the map to fill the container
    const effectiveWidth = width;
    
    // Make map responsive to container size
    window.addEventListener('resize', resizeMap);
    
    function resizeMap() {
      // Update dimensions
      const newWidth = container.clientWidth;
      const newHeight = container.clientHeight;
      
      // Adjust projection
      projection.fitSize([newWidth, newHeight], worldFC);
      
      // Update paths
      countryLayer.selectAll("path.country")
        .attr("d", path);
      
      // Update markers
      updateMarkers();
    }
    
    // Zoom function
    function zoomed(event) {
      const { transform } = event;
      mapGroup.attr("transform", transform);
      
      // Adjust marker size based on zoom level
      const markerBaseSize = 120;
      const newSize = markerBaseSize / transform.k;
      markerLayer.selectAll(".marker")
        .attr("d", d3.symbol().type(d3.symbolCircle).size(newSize));
      
      // Adjust stroke width based on zoom
      countryLayer.selectAll(".country")
        .style("stroke-width", 0.5 / transform.k);
    }
    
    function updateMarkers() {
      markerLayer.selectAll(".marker-container")
        .attr("transform", d => {
          const [mx, my] = projection(d.coords);
          return `translate(${mx}, ${my})`;
        });
        
      // 更新区域标签位置
      labelLayer.selectAll("text.map-region-label")
        .attr("x", d => projection(d.center)[0])
        .attr("y", d => projection(d.center)[1] - 40);
    }
    
    // Zoom control buttons
    document.getElementById("zoomIn").addEventListener("click", function() {
      svg.transition().duration(500).call(zoom.scaleBy, 1.5);
    });
    
    document.getElementById("zoomOut").addEventListener("click", function() {
      svg.transition().duration(500).call(zoom.scaleBy, 0.75);
    });
    
    document.getElementById("resetMap").addEventListener("click", function() {
      svg.transition().duration(750).call(
        zoom.transform,
        d3.zoomIdentity
      );
    });

    let isPopupSticky = false; // Track if popup should stay open
    let hidePopupTimeout; // Timeout to hide popup with delay
    let activeMarker = null; // 跟踪当前活动的标记
    
    // Mouse is over popup flag
    let isMouseOverPopup = false;
    
    // Global variable to store our data for later use
    let worldFC;

    const schools = [
    {
        name: "Hamden Hall Country Day School",
        coords: [-72.93, 41.40],
        info: "Address: 1108 Whitney Ave, Hamden, Ct, 06516. Its Carbon Footprint Club is the major contributor to our Initiative.",
        region: "North America"
      },
      {
        name: "Kingswood Oxford School",
        coords: [-72.75, 41.78],
        info: "Address: 170 Kingswood Rd, West Hartford, CT 06119. Its material club is one of our major collaborators.",
        region: "North America"
      },
      {
        name: "Shanghai Starriver Bilingual School",
        coords: [121.2, 31.2],
        info: "Address: 上海市闵行区金都路2588号. A bilingual School in Shanghai, China, with a profound focus on sustainability, one of the participants of our Initiative.",
        region: "Asia"
      },
      {
        name: "Baylor School",
        coords: [-85.3, 35.08],
        info: "Address: 171 Baylor School Rd, Chattanooga, TN, 37405. It has a strong focus on sustainability and environmental education, one of the participants of our Initiative.",
        region: "North America"
      },
      {
        name: "Hiba Academy shanghai",
        coords: [121.2, 31.4],
        info: "Address: 上海市浦东新区林耀路235号. A bilingual School in Shanghai, China, with a profound focus on sustainability, one of the participants of our Initiative",
        region: "Asia"
      },
      {
        name: "Shanghai Qingpu Pinghe Bilingual School",
        coords: [121.4, 31.1],
        info: "Address: 上海市青浦区朱家角路6号. A bilingual School in Shanghai, China, with a profound focus on sustainability, one of the participants of our Initiative",
        region: "Asia"
      },
      {
        name: "The Bryn Mawr School",
        coords: [-76.63, 39.37],
        info: "Address: 109 W Melrose Ave, Baltimore, MD 21210. It has a great focus on sustainability and environmental education, one of the participants of our Initiative",
        region: "North America"
      },
      {
        name: "上海市世界外国语中学",
        coords: [121.4, 31.2],
        info: "Address: 中国上海市虹漕南路602号. An international School in Shanghai, China, with a profound focus on sustainability, one of the first participants of our Initiative",
        region: "Asia"
      },
      {
        name: "广东碧桂园学校",
        coords: [113.16, 22.56],
        info: "Address: Shunde District, Foshan, China, 511419. An international School in Guangdong, China, with a profound focus on sustainability, one of the participants of our Initiative",
        region: "Asia"
      },
      {
        name: "King's School Canterbury",
        coords: [5.02, 51.16],
        info:"Address: 25 The Precincts, Canterbury CT1 2ES, United Kingdom. It has a great focus on sustainability and environmental education, one of the participants of our Initiative",
        region: "Europe"
      }
    ];

    // Popup functions with smooth bounce animation
    const popup = d3.select("#popup");
    function showPopup(event, htmlContent) {
      // Use d3.pointer for coordinates relative to the map container
      const [x, y] = d3.pointer(event, container);
      
      popup.html(htmlContent);

      // Get popup dimensions after setting content but before displaying
      popup.style("display", "block")
           .style("visibility", "hidden"); // Temporarily hide while calculating position
      
      const popupWidth = popup.node().offsetWidth;
      const popupHeight = popup.node().offsetHeight;
      const mapRect = container.getBoundingClientRect();
      
      // Check if we're on a mobile device (less than 768px width)
      const isMobile = window.innerWidth <= 768;

      // Calculate position to avoid edge overflow
      let left = x + 15;
      let top = y - 15;
      
      // Special mobile positioning - center wider popups horizontally
      if (isMobile) {
        // Center horizontally if enough space
        left = Math.max(10, Math.min(mapRect.width - popupWidth - 10, x - (popupWidth / 2)));
        
        // For vertical positioning on mobile, prefer showing below the tap point
        // This avoids the finger/thumb covering the popup when tapping
        if (y + popupHeight + 30 <= mapRect.height) {
          top = y + 30; // Position below finger/tap point
        } else if (y - popupHeight - 30 >= 0) {
          top = y - popupHeight - 30; // Position above if there's room
        } else {
          // If neither above nor below fits well, center in the visible area
          top = Math.max(10, Math.min(mapRect.height - popupHeight - 10, (mapRect.height - popupHeight) / 2));
        }
      } else {
        // Desktop positioning logic
        // Special positioning for east Asia region (China markers)
        // Check if marker is in the right side of the map
        if (x > mapRect.width * 0.75) {
          // Force display to the left for right-side markers
          left = x - popupWidth - 15;
        } else if (left + popupWidth > mapRect.width) {
          // For other markers, adjust if would overflow right edge
          left = x - popupWidth - 15; 
        }
        
        // Adjust if would overflow bottom edge
        if (top + popupHeight > mapRect.height) {
          top = Math.max(5, mapRect.height - popupHeight - 10); // Keep within map with small margin
        }
        
        // Adjust if would overflow top edge
        if (top < 5) {
          top = 5; // Maintain small margin from top
        }
      }

      // Apply final position and make visible
      popup.style("left", left + "px")
           .style("top", top + "px")
           .style("visibility", "visible");
    }
    
    function hidePopup() {
      popup.style("display", "none")
           .style("visibility", "hidden");
    }

    // Add event listeners to popup for mouse enter/leave
    popup.on("mouseenter", function() {
      isMouseOverPopup = true;
      // Clear any pending hide timeouts
      if (hidePopupTimeout) {
        clearTimeout(hidePopupTimeout);
        hidePopupTimeout = null;
      }
    }).on("mouseleave", function() {
      isMouseOverPopup = false;
      // Only hide if not sticky
      if (!isPopupSticky) {
        hidePopup();
      }
    });

    // Enhanced marker mouseenter with active state
    function markerMouseEnter(event, d) {
      event.stopPropagation(); // 防止事件冒泡
      
      // 如果有一个活动的标记，并且是不同的标记，则不执行任何操作
      if (isPopupSticky && activeMarker && activeMarker !== this) {
        return;
      }
      
      // Highlight this marker
      d3.select(this.parentNode).classed("active", true);
      
      // Calculate cluster info
      const [baseX, baseY] = projection(d.coords);
      const cluster = [];
      markerLayer.selectAll(".marker-container").each(function(d2) {
        // Skip self comparison
        if (d === d2) return;
        const [bx, by] = projection(d2.coords);
        const dx = bx - baseX, dy = by - baseY;
        // Increase distance threshold for cluster detection
        if (Math.sqrt(dx * dx + dy * dy) < 40) { 
          cluster.push(d2);
          // Highlight clustered markers also
          d3.select(this).classed("active", true);
        }
      });
      
      // Generate HTML content
      let htmlContent;
      // Combine hovered marker + cluster
      const displayItems = [d].concat(cluster);
      
      if (displayItems.length > 1) {
        htmlContent = `<h3>Schools in ${d.region}:</h3><ul>`;
        displayItems.forEach(school => {
           htmlContent += `<li><strong>${school.name}</strong><br>${school.info}</li>`;
        });
        htmlContent += "</ul>";
      } else {
        // Only the single hovered marker
        htmlContent = `<h3>${d.name}</h3><p><strong>Region:</strong> ${d.region}</p><p>${d.info}</p>`;
      }
      
      // Show popup directly using event coordinates relative to container
      showPopup(event, htmlContent);
    }
    
    function markerMouseLeave(event, d) {
      event.stopPropagation(); // 防止事件冒泡
      
      // 如果标记已固定，则不响应鼠标离开事件
      if (isPopupSticky && activeMarker) {
        return;
      }
      
      // Remove highlight if not clicked
      if (!isPopupSticky) {
        markerLayer.selectAll(".marker-container").classed("active", false);
      }
      
      // Hide popup only if it's not sticky (i.e., not clicked),
      // and use a timeout to allow moving to the popup
      if (!isPopupSticky) {
        // Clear any existing timeout
        if (hidePopupTimeout) {
          clearTimeout(hidePopupTimeout);
        }
        
        // Set a short delay to check if mouse moved to popup
        hidePopupTimeout = setTimeout(() => {
          if (!isMouseOverPopup) {
      hidePopup(); 
          }
        }, 300); // 300ms delay
      }
    }

    // Updated click handling with improved interaction
    function markerClick(event, d) {
      event.stopPropagation(); // 防止事件冒泡
      
      // 如果点击的是当前活动的标记，则切换状态
      if (activeMarker === this) {
        isPopupSticky = !isPopupSticky;
        if (!isPopupSticky) {
          // 如果取消固定，隐藏弹出窗口并重置活动标记
          hidePopup();
          markerLayer.selectAll(".marker-container").classed("active", false);
          activeMarker = null;
          return;
        }
      } else {
        // 如果点击的是新标记，设置为固定状态
        isPopupSticky = true;
        // 重置之前的活动标记
        markerLayer.selectAll(".marker-container").classed("active", false);
      }
      
      // 设置当前标记为活动标记
      activeMarker = this;
      
      // Add active class to this marker
      d3.select(this.parentNode).classed("active", true);
      
      // Check if we're on mobile
      const isMobile = window.innerWidth <= 768;
      
      // If clicked, show popup with enhanced content
      let enhancedContent;
      
      if (isMobile) {
        // Simpler content for mobile
        enhancedContent = `
          <h3>${d.name}</h3>
          <p><strong>Region:</strong> ${d.region}</p>
          <p>${d.info}</p>
          <p style="text-align: center; margin-top: 10px;">
            <a href="#" id="zoom-to-school" style="color: var(--ios-blue); font-size: 14px; display: inline-block; padding: 6px 0;">
              <i class="fas fa-search-plus"></i> Zoom to location
            </a>
          </p>
        `;
      } else {
        // Regular content for desktop
        enhancedContent = `
          <h3>${d.name}</h3>
          <p><strong>Region:</strong> ${d.region}</p>
          <p>${d.info}</p>
          <p style="text-align: center; margin-top: 15px;">
            <a href="#" id="zoom-to-school" style="color: var(--ios-blue);">
              <i class="fas fa-search-plus"></i> Zoom to location
            </a>
          </p>
        `;
      }
      
      showPopup(event, enhancedContent);
      
      // Add zoom to location functionality
      setTimeout(() => {
        const zoomBtn = document.getElementById("zoom-to-school");
        if (zoomBtn) {
          zoomBtn.addEventListener("click", function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            // Calculate the pixel coordinates of the school
            const [x, y] = projection(d.coords);
            
            // Create a transform that centers on the school and zooms in
            const scale = isMobile ? 4 : 5; // Slightly less zoom on mobile
            const translate = [width / 2 - x * scale, height / 2 - y * scale];
            
            // Apply the transform with smooth transition
            svg.transition()
              .duration(750)
              .call(
                zoom.transform,
                d3.zoomIdentity
                  .translate(translate[0], translate[1])
                  .scale(scale)
              );
            
            // On mobile, hide the popup after zooming to give more map visibility
            if (isMobile) {
              setTimeout(() => {
                hidePopup();
                isPopupSticky = false;
                activeMarker = null;
                markerLayer.selectAll(".marker-container").classed("active", false);
              }, 800);
            }
          });
        }
      }, 100);
    }

    // Country hover effect
    function countryMouseOver(event, d) {
      // 如果弹出窗口已固定，不执行悬停效果
      if (isPopupSticky) return;
      
      d3.select(this)
        .classed("hover", true); // 不再使用raise()方法避免覆盖标记
        
      // Get country name
      const countryName = d.properties.name;
      
      // Find schools in this country
      const schoolsInCountry = schools.filter(school => {
        // This is a simple approximation - in a real app you would use more precise geospatial checks
        const [lon, lat] = school.coords;
        const point = projection([lon, lat]);
        const isInside = d3.geoContains(d, [lon, lat]);
        return isInside;
      });
      
      if (schoolsInCountry.length > 0) {
        let content;
        // Check if on mobile for simpler display
        const isMobile = window.innerWidth <= 768;
        
        if (isMobile && schoolsInCountry.length > 2) {
          // Simplified content for mobile with many schools
          content = `<h3>${countryName}</h3>`;
          content += `<p>Contributors: <strong>${schoolsInCountry.length}</strong> schools</p>`;
          // Just list the names without additional details to save space
          content += "<ul style='margin-bottom: 5px;'>";
          schoolsInCountry.forEach(school => {
            content += `<li><strong>${school.name}</strong></li>`;
          });
          content += "</ul>";
          content += "<p style='font-size: 12px; margin-top: 5px;'>Tap a school marker for details</p>";
        } else {
          // Standard content for desktop or mobile with few schools
          content = `<h3>${countryName}</h3>`;
          content += `<p>Contributors: <strong>${schoolsInCountry.length}</strong> schools</p>`;
          content += "<ul>";
          schoolsInCountry.forEach(school => {
            content += `<li><strong>${school.name}</strong></li>`;
          });
          content += "</ul>";
        }
        
        showPopup(event, content);
      }
    }
    
    function countryMouseOut(event, d) {
      d3.select(this).classed("hover", false);
      
      // 不再立即隐藏popup
      // if (!isPopupSticky) {
      //   hidePopup();
      // }
      
      // 如果弹出窗口已固定，不执行鼠标离开效果
      if (isPopupSticky) return;
      
      if (!isPopupSticky) {
        // Clear any existing timeout
        if (hidePopupTimeout) {
          clearTimeout(hidePopupTimeout);
        }
        
        // Set a short delay to check if mouse moved to popup
        hidePopupTimeout = setTimeout(() => {
          if (!isMouseOverPopup) {
            hidePopup();
          }
        }, 300); // 300ms delay
      }
    }

    function countryClick(event, d) {
      // 如果弹出窗口已固定，先清除它
      if (isPopupSticky) {
        hidePopup();
        isPopupSticky = false;
        activeMarker = null;
        markerLayer.selectAll(".marker-container").classed("active", false);
      }
      
      // Get bounds of the country
      const bounds = path.bounds(d);
      const dx = bounds[1][0] - bounds[0][0];
      const dy = bounds[1][1] - bounds[0][1];
      const x = (bounds[0][0] + bounds[1][0]) / 2;
      const y = (bounds[0][1] + bounds[1][1]) / 2;
      
      // Calculate appropriate scale
      const scale = Math.max(1, Math.min(8, 0.9 / Math.max(dx / width, dy / height)));
      
      // Transition to the country
      svg.transition().duration(750).call(
        zoom.transform,
        d3.zoomIdentity
          .translate(width / 2, height / 2)
          .scale(scale)
          .translate(-x, -y)
      );
    }

    // Load and render the world map
    d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson")
      .then(world => {
        const worldData = world.features.filter(d => d.properties.name !== "Antarctica");
        worldFC = { type: "FeatureCollection", features: worldData };
        
        // Fit map to the container
        projection.fitSize([effectiveWidth, height], worldFC);
        
        // Render countries with improved styling and interactions
        countryLayer.selectAll("path.country")
          .data(worldData)
          .enter()
          .append("path")
          .attr("class", "country")
          .attr("d", path)
          .attr("data-name", d => d.properties.name)
          .on("mouseover", countryMouseOver)
          .on("mouseout", countryMouseOut)
          .on("click", countryClick);
        
        // Add gradient defs for marker effects
        const defs = svg.append("defs");
        
        // Create radial gradient for markers
        const gradient = defs.append("radialGradient")
          .attr("id", "marker-gradient")
          .attr("cx", "50%")
          .attr("cy", "50%")
          .attr("r", "50%");
        
        gradient.append("stop")
          .attr("offset", "0%")
          .attr("stop-color", "var(--marker-fill-light)")
          .attr("stop-opacity", 1);
          
        gradient.append("stop")
          .attr("offset", "100%")
          .attr("stop-color", "var(--marker-fill-light)")
          .attr("stop-opacity", 0.7);
        
        // Create enhanced marker groups with pulsing effect
        const markerContainers = markerLayer.selectAll("g.marker-container")
          .data(schools)
          .enter()
          .append("g")
          .attr("class", "marker-container")
          .attr("transform", d => {
            const [mx, my] = projection(d.coords);
            return `translate(${mx}, ${my})`;
          });
        
        // Add pulsing circle behind markers for visual effect
        markerContainers.append("circle")
          .attr("class", "marker-pulse")
          .attr("r", 5)
          .attr("fill", "var(--marker-fill-light)");
        
        // Add the main marker with improved styling
        markerContainers.append("path")
          .attr("class", "marker")
          .attr("d", d3.symbol().type(d3.symbolCircle).size(120))
          .attr("fill", "url(#marker-gradient)")
          .on("mouseenter", markerMouseEnter)
          .on("mouseleave", markerMouseLeave)
          .on("click", markerClick);
        
        // Add region labels
        const regions = {};
        schools.forEach(school => {
          if (!regions[school.region]) {
            regions[school.region] = {
              name: school.region,
              schools: [],
              center: [0, 0]
            };
          }
          regions[school.region].schools.push(school);
        });
        
        // Calculate region centers from schools
        Object.values(regions).forEach(region => {
          const sumCoords = region.schools.reduce((sum, school) => {
            return [sum[0] + school.coords[0], sum[1] + school.coords[1]];
          }, [0, 0]);
          
          region.center = [
            sumCoords[0] / region.schools.length,
            sumCoords[1] / region.schools.length
          ];
        });
        
        // Add labels for regions
        labelLayer.selectAll("text.map-region-label")
          .data(Object.values(regions))
          .enter()
          .append("text")
          .attr("class", "map-region-label")
          .attr("x", d => projection(d.center)[0])
          .attr("y", d => projection(d.center)[1] - 40) // Position above marker clusters
          .text(d => `${d.name} (${d.schools.length})`);
      });
      
    // Close popup when clicking outside of markers
    svg.on("click", function(event) {
      // 如果事件已经被处理了，则不执行
      if (event.defaultPrevented) return;
      
      // 重置状态
      hidePopup();
      isPopupSticky = false;
      activeMarker = null;
      markerLayer.selectAll(".marker-container").classed("active", false);
      });
  </script>
</body>
</html>
